<?php
require_once '../conn/ppconfig.php';

//turn php errors on
ini_set("track_errors", true);

//set PayPal Endpoint to sandbox
$url = trim("https://svcs.sandbox.paypal.com/AdaptivePayments/Pay");

/*
*******************************************************************
PayPal API Credentials
Replace <API_USERNAME> with your API Username
Replace <API_PASSWORD> with your API Password
Replace <API_SIGNATURE> with your Signature
*******************************************************************
*proactivesport@gmail.com
*#UnitF110
*brains4me
*/

//PayPal API Credentials
//$API_UserName = "andrew_api1.falsado.com"; //TODO
//$API_Password = "ZP7H7JB7XE6N32EP"; //TODO
//$API_Signature = "A2R3a0inlbljLmS0gtjg4fktI6ULAYuqKQKWa6duecu9pkFKQ-Ir1bzM"; //TODO
	
//Default App ID for Sandbox	 URXZGENYFLLNS
$API_AppID = "APP-1JE4291016473214C"; //APP-80W284485P519543T";

$API_RequestFormat = "NV";
$API_ResponseFormat = "NV";

$returnURL = $url."paymentdetails.php";
$cancelURL = $url. "paymentcancel.php" ;
$receiverEmail = $url. "/SetPay.php" ;
		           
//Create request payload with minimum required parameters
$bodyparams = array (	"requestEnvelope.errorLanguage" => "en_US",
											"actionType" => "PAY",
											"currencyCode" => "PHP",
											"cancelUrl" => $cancelURL,
											"returnUrl" => $returnURL,
											"receiverList.receiver(0).email" => $receiverEmail, //TODO
											"receiverList.receiver(0).amount" => "1" //TODO
											);
											
// convert payload array into url encoded query string
$body_data = http_build_query($bodyparams, "", chr(38));


try
{

    //create request and add headers
    $params = array("http" => array( "method" => "POST",
                  					"content" => $body_data,
                  					"header" =>  "X-PAYPAL-SECURITY-USERID: " . PPAPI_USERNAME . "\r\n" .
                               		"X-PAYPAL-SECURITY-SIGNATURE: " . PPAPI_SIGNATURE . "\r\n" .
                 					"X-PAYPAL-SECURITY-PASSWORD: " . PPAPI_PASSWORD . "\r\n" .
                   					"X-PAYPAL-APPLICATION-ID: " . $API_AppID . "\r\n" .
                   					"X-PAYPAL-REQUEST-DATA-FORMAT: " . $API_RequestFormat . "\r\n" .
                  					"X-PAYPAL-RESPONSE-DATA-FORMAT: " . $API_ResponseFormat . "\r\n" 
                  					));


    //create stream context
     $ctx = stream_context_create($params);
    

    //open the stream and send request
     $fp = @fopen($url, "r", false, $ctx);

    //get response
  	 $response = stream_get_contents($fp);

  	//check to see if stream is open
     if ($response === false) {
        throw new Exception("php error message = " . "$php_errormsg");
     }
           
    //close the stream
     fclose($fp);

    //parse the ap key from the response
    $keyArray = explode("&", $response);
        
    foreach ($keyArray as $rVal){
    	list($qKey, $qVal) = explode ("=", $rVal);
			$kArray[$qKey] = $qVal;
    }
       
    //set url to approve the transaction https://www.sandbox.paypal.com/webscr&cmd=
    //$payPalURL = "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=" . $kArray["payKey"];
    $payPalURL = PAYPAL_REDIRECT_URL . "_ap-payment&paykey=" . $kArray["payKey"];

    //print the url to screen for testing purposes
    /*If ( $kArray["responseEnvelope.ack"] == "Success") {
    	echo '<p><a href="' . $payPalURL . '" target="_blank">' . $payPalURL . '</a></p>';
     }
    else {
    	echo 'ERROR Code: ' .  $kArray["error(0).errorId"] . " <br/>";
      echo 'ERROR Message: ' .  urldecode($kArray["error(0).message"]) . " <br/>";
    }*/
   
    
   	//optional code to redirect to PP URL to approve payment
    If ( $kArray["responseEnvelope.ack"] == "Success") {
   
  	  header("Location:".  $payPalURL);
      exit;
	}
    else {
     		echo 'ERROR Code: ' .  $kArray["error(0).errorId"] . " <br/>";
        	echo 'ERROR Message: ' .  urldecode($kArray["error(0).message"]) . " <br/>";
     }
     
}

catch(Exception $e) {
  	echo "Message: ||" .$e->getMessage()."||";
  }

?>
